package com.ericsson.enap.modules.procLog.task;

import cn.hutool.core.util.CharsetUtil;
import com.ericsson.common.util.LogFileName;
import com.ericsson.common.util.LoggerUtils;
import com.ericsson.enap.modules.procLog.entity.ProcLogCsv;
import com.ericsson.enap.modules.procLog.utils.ProcLogUtil;
import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.CsvToBeanBuilder;
import com.opencsv.bean.HeaderColumnNameMappingStrategy;
import org.slf4j.Logger;
import org.springframework.data.mongodb.core.MongoTemplate;

import java.io.*;
import java.util.*;

/**
 * @description:procLog解析task
 * @author: wangjingshi
 * @create: 2021-05-06 19:25
 */
public class ProcLogDealTask implements Runnable{

    private Logger log = LoggerUtils.Logger(LogFileName.EbmLogJob);

    private Long netId;
    private String localPath;
    private MongoTemplate mongoTemplate;
    private String collectionName;
    private String netName;

    public ProcLogDealTask(Long netId, String localPath, MongoTemplate mongoTemplate, String collectionName,String netName) {
        this.netId = netId;
        this.localPath = localPath;
        this.mongoTemplate = mongoTemplate;
        this.collectionName = collectionName;
        this.netName = netName;
    }

    @Override
    public void run() {
        File file = new File(localPath);
        System.out.println("------------- localPath:"+localPath);
        //1、过滤筛选出gz文件
        String[] gzDir = file.list(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                if (name.endsWith(".gz")) {
                    return true;
                }
                return false;
            }
        });
        for (int i = 0; i < gzDir.length; i++) {
            System.out.println("--------------localPath+File.separator+dir[i]:"+localPath+File.separator+gzDir[i]);
            File f = new File(localPath+File.separator+gzDir[i]);
            //1、解压gz文件成csv
            log.info("==========================  uncompress start  =========================");
            ProcLogUtil.uncompress(f, localPath+File.separator);
            log.info("==========================  uncompress end  =========================");
        }


        File csvfile = new File(localPath);
        //1、过滤筛选出csv文件
        String[] csvDir = csvfile.list(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                if (name.endsWith(".csv")) {
                    return true;
                }
                return false;
            }
        });
        //2、遍历csv,并解析文件
        for (int i = 0; i < csvDir.length; i++) {
            File f = new File(localPath+File.separator+csvDir[i]);
            try {
                List<ProcLogCsv> list = this.parseByName(f);
                Map<String,String> map = new HashMap<>();
                for(ProcLogCsv temp:list){
                    String rootLogId = temp.getRootLogId();
                    String instance = temp.getInstance();
                    if(map.containsKey(rootLogId)){
                        temp.setInstance(map.get(rootLogId));
                    }else{
                        map.put(rootLogId,instance);
                    }
                    String logType = temp.getLogType();
                    logType = logType.equals("northbound")?"2":"1";
                    String status = temp.getStatus();
                    status = status.equals("SUCCESSFUL")?"1":"2";
                    temp.setLogType(logType);
                    temp.setStatus(status);
                    temp.setEdaId(netId);
                    if(netId==40L){
                        temp.setEda("EDA01");
                    }else{
                        temp.setEda("EDA02");
                    }
                }
                log.info("net: "+ netId +" list: "+list.size());
                mongoTemplate.insert(list,collectionName);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        long endTime = new Date().getTime();
        log.info("net: "+ netId +" ===== do ProcLogTask end =====: "+endTime);
    }


    //解析csv文件
    public List<ProcLogCsv> parseByName(File file) throws IOException {
        InputStreamReader inputStream = new InputStreamReader(new FileInputStream(file), CharsetUtil.CHARSET_GBK);
        // 设置解析策略，csv的头和POJO属性的名称对应，也可以使用@CsvBindByName注解来指定名称
        HeaderColumnNameMappingStrategy strategy = new HeaderColumnNameMappingStrategy();
        strategy.setType(ProcLogCsv.class);
        CsvToBean csvToBean = new CsvToBeanBuilder(inputStream)
                .withMappingStrategy(strategy)
                .build();
        List<ProcLogCsv> list = csvToBean.parse();
        return list;
    }

    private String generateUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
}
